/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.vaadin.data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import javax.xml.xpath.XPathFunction;
import javax.xml.xpath.XPathFunctionException;

import org.w3c.dom.NodeList;

public class Iso8601DateFormatFunction implements XPathFunction {
    public static final String format = "yyyy-MM-dd'T'HH:mm:ssZ";

    private TimeZone outputTimeZone = TimeZone.getDefault();

    public Object evaluate(List args) throws XPathFunctionException {

        try {
            NodeList nl = (NodeList) args.get(0);

            String s = nl.item(0).getNodeValue();

            if (s != null && s.toLowerCase().endsWith("z")) {
                s = s.substring(0, s.length() - 1);
                s = s + "+0000";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(outputTimeZone);
            return sdf.format(sdf.parse(s));

        } catch (ParseException e) {
            return "ERROR";
        }
    }

    public void setOutputTimeZone(TimeZone tz) {
        outputTimeZone = tz;
    }

}
